package address

import (
	"context"
	"strings"

	"mall/common/jwt"
	"mall/common/resultx"
	"mall/common/utils/pointy"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"
	"mall/service/user/rpc/userclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateUserAddressLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 修改UserAddress
func NewUpdateUserAddressLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateUserAddressLogic {
	return &UpdateUserAddressLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateUserAddressLogic) UpdateUserAddress(
	req *types.UpdateUserAddressReq,
	headers *[]*types.Header,
) (resp *types.BaseMsgResp, err error) {
	if req.Id == nil || *req.Id == 0 {
		return nil, resultx.NewErrCode(resultx.USER_ADDRESS_ID_REQUIRED)
	}

	if req.Consignee != nil && len(strings.TrimSpace(*req.Consignee)) == 0 {
		return nil, resultx.NewErrCode(resultx.USER_ADDRESS_CONSIGNEE_REQUIRED)
	}

	if req.Mobile != nil && len(strings.TrimSpace(*req.Mobile)) == 0 {
		return nil, resultx.NewErrCode(resultx.USER_ADDRESS_CONSIGNEE_REQUIRED)
	}

	if req.DetailedAddress != nil && len(strings.TrimSpace(*req.DetailedAddress)) == 0 {
		return nil, resultx.NewErrCode(resultx.USER_ADDRESS_ADDRESS_REQUIRED)
	}

	userId := jwt.GetUserId(l.ctx)
	if userId == 0 {
		return nil, resultx.NewErrCode(resultx.TOKEN_EXPIRE_ERROR)
	}

	var geographic []*userclient.UserMetaInfo
	if len(req.Geographic) > 0 {
		for _, v := range req.Geographic {
			geographic = append(geographic, &userclient.UserMetaInfo{
				Key:   v.Key,
				Label: v.Label,
				Value: v.Value,
			})
		}
	}

	_, err = l.svcCtx.UserRpc.UpdateUserAddress(l.ctx, &userclient.UserAddressInfo{
		Id:              req.Id,
		UserId:          pointy.GetPointer(userId),
		Label:           req.Label,
		Consignee:       req.Consignee,
		Mobile:          req.Mobile,
		DetailedAddress: req.DetailedAddress,
		PostalCode:      req.PostalCode,
		IsDefault:       req.IsDefault,
		Geographic:      geographic,
		VisitorId:       pointy.GetPointer(userId),
	})
	if err != nil {
		return nil, err
	}

	return &types.BaseMsgResp{
		Msg: "修改地址成功",
	}, nil
}
